package com.glela.order.service.impl.order;

import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.service.SMSService;
import com.glela.common.util.DateUtil;
import com.glela.common.util.JsonUtil;
import com.glela.common.util.StringUtil;
import com.glela.order.mapper.OrderSettlementCommisionMapper;
import com.glela.order.model.OrderInfo;
import com.glela.order.model.OrderObject;
import com.glela.order.model.OrderSettlementCommision;
import com.glela.order.service.OrderInfoService;
import com.glela.order.service.OrderService;
import com.glela.order.service.impl.NotifyWxMsgServiceImpl;
import com.glela.platform.model.BaseRestrictions;
import com.glela.platform.model.OperationLog;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.OperationLogService;
import com.glela.platform.service.UserService;

/**
 * **********************************************
 * @Title: 结算分佣单监听队列
 * @throws @author gaoweiqi
 * @date 2017年12月25日 下午5:21:27 **********************************************
 */
public class AmqpAddCommision implements MessageListener {

	private static Logger logger = LoggerFactory.getLogger(AmqpAddCommision.class);
	private OrderService orderService2;
	@Autowired
	private NotifyWxMsgServiceImpl notifyWxMsgServiceImpl;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private UserService userService;
	@Autowired
	private SMSService smsService;
	@Autowired
	private OrderInfoService orderInfoService;
	@Autowired
	private OperationLogService operationLogService;
	@Autowired
	private OrderSettlementCommisionMapper orderSettlementCommisionMapper;

	@Override
	public void onMessage(Message arg0) {
		String orderThing = null;
		OrderSettlementCommision temp = null;
		try {
			//转换消息实体
			orderThing = new String(arg0.getBody());
			temp = JsonUtil.toBean(orderThing, OrderSettlementCommision.class);
		} catch (Exception e) {
			logger.error("分佣结算处理队列接收消息错误：{}-{}", orderThing, e.getMessage());
		}
		try {
			if (temp != null && temp.getStatus() == 3) {//开始处理
				//添加结算单 分佣信息
				boolean rslt = orderService2.addOrder_settlement_commision(temp);
				if (rslt) {
					//发送微信模版消息-推荐销售成功 
					notifyWxMsgServiceImpl.sendWxTemplateMsgMarketingSuccess(temp.getOrderObjectId());
					//发送下单短信
					OrderObject objorder = orderService2.selectOrderObjectByOrderSn(temp.getOrderSn());
					if (objorder.getOpenStoreUserId() != null) {// 有店中店用户 判断是不是店主  如果是店主就发短息
						ResponseUser OpenStoreUser = userService.selectUserRoleById(objorder.getOpenStoreUserId());
						if (OpenStoreUser != null && ArrayUtils.contains(new int[] { 3, 4, 7, 11 }, OpenStoreUser.getRoleId())) {// 是店主 发短信
							ResponseUser PayOrderUser = userService.selectUserRoleById(objorder.getUserId());
							if (PayOrderUser != null && !StringUtils.isAnyBlank(PayOrderUser.getUserName(), OpenStoreUser.getUserName())) {// 准备短信内容
								BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.PAY_ORDER_SMS.getText());
								if (baseRestrictions != null && baseRestrictions.getStatus() == 1) {// 需要发送短信
									List<OrderInfo> listorderinfo = orderInfoService.selectOrderInfoByOrderObjectIdC(objorder.getId());
									for (OrderInfo orderInfo : listorderinfo) {
										// PayOrderPhone在你的小铺下单啦！订单编号:orderSn【小铺来了】
										String SMS = baseRestrictions.getName().replace("PayOrderPhone", StringUtil.replaceChars(3, 2, PayOrderUser.getUserName())).replace("orderSn", orderInfo.getOrderSn()).replace("amount", String.valueOf((orderInfo.getCommisionFee() + orderInfo.getPointFee()) / 100.0));
										long responseSMS = smsService.sendMsgJianZhou(false, OpenStoreUser.getUserName(), SMS);// 立即发送短信
										if (responseSMS < 0) {
											logger.error("下单发送短信失败：下单人：{}，短信接收人:{}", PayOrderUser.getUserName(), OpenStoreUser.getUserName());
										}
										// 短信日志
										OperationLog log = new OperationLog();
										log.setObjId(OpenStoreUser.getUserId().intValue());
										log.setObjName(String.valueOf(OpenStoreUser.getNickName()));
										log.setModule("PayOrderCallOpenStoreUser");
										log.setOperateType("sendSms");
										Long createLongTime = ((new Date().getTime()) / 1000);
										log.setCreatedAt(createLongTime.intValue());
										log.setDescription("下单短信提醒" + SMS);
										operationLogService.saveOperateLog(log);
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			orderSettlementCommisionMapper.updateStatus(e.getMessage().length() > 100 ? e.getMessage().substring(0, 100) : e.getMessage(), 5, orderSettlementCommisionMapper.selectByorderSn(temp.getOrderSn()).getStatus(), DateUtil.getNow(), temp.getId());
			logger.error("分佣结算处理队列错误：{}-{}", arg0, e.getMessage());
		}
	}

	public void setOrderService2(OrderService orderService2) {
		this.orderService2 = orderService2;
	}
}
